<template>
  <div class="resource-admin-container">
    <a-card class="section-card">
      <div class="table-toolbar">
        <div class="left">
          <a-input-search
            v-model:value="searchParams.searchText"
            placeholder="搜索资源名称/描述"
            style="width: 250px"
            @search="handleSearch"
          />
          <a-select
            v-model:value="searchParams.type"
            placeholder="资源类型"
            style="margin-right: 16px; width: 150px; margin-left: 16px"
            allowClear
            @change="handleSearch"
          >
            <a-select-option value="document">文档</a-select-option>
            <a-select-option value="image">图片</a-select-option>
            <a-select-option value="video">视频</a-select-option>
            <a-select-option value="audio">音频</a-select-option>
            <a-select-option value="other">其他</a-select-option>
          </a-select>
          <a-input-search
            v-model:value="searchParams.userName"
            placeholder="输入资源上传者"
            style="width: 250px"
            @search="handleSearch"
          />
        </div>
        <div class="right">
          <a-button
            style="margin-left: 8px"
            @click="handleBatchDelete"
            :disabled="selectedRowKeys.length === 0"
          >
            <delete-outlined /> 批量删除
          </a-button>
          <a-button style="margin-left: 8px" @click="fetchData()">
            <reload-outlined /> 刷新
          </a-button>
        </div>
      </div>

      <a-table
        :columns="columns"
        :data-source="dataList"
        :pagination="pagination"
        :loading="loading"
        :row-selection="{ selectedRowKeys, onChange: onSelectChange }"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'id'">
            <span>{{ record.id }}</span>
          </template>

          <template v-if="column.key === 'preview'">
            <div class="resource-preview">
              <file-pdf-outlined v-if="record.type === 'pdf'" />
              <file-word-outlined v-else-if="record.type === 'doc'" />
              <file-word-outlined v-else-if="record.type === 'docx'" />
              <file-excel-outlined v-else-if="record.type === 'xlsx'" />
              <file-ppt-outlined v-else-if="record.type === 'pptx'" />
              <picture-outlined v-else-if="record.type === 'image'" />
              <video-camera-outlined v-else-if="record.type === 'video'" />
              <sound-outlined v-else-if="record.type === 'audio'" />
              <file-outlined v-else />
            </div>
          </template>

          <template v-if="column.key === 'type'">
            <a-tag :color="getTypeColor(record.type)">
              {{ getTypeText(record.type) }}
            </a-tag>
          </template>

          <template v-if="column.key === 'status'">
            <a-badge
              :status="record.status === 2 ? 'success' : 'default'"
              :text="record.status === 2 ? '可用' : '已禁用'"
            />
          </template>
          <template v-else-if="column.dataIndex === 'publishTime'">
            {{ dayjs(record.publishTime).format('YYYY-MM-DD') }}
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="() => handlePreview(record)">预览</a>
              <a-divider type="vertical" />
              <a @click="() => handleDownload(record)">下载</a>
              <a-divider type="vertical" />
              <a-dropdown>
                <a class="ant-dropdown-link" @click.prevent> 更多 <down-outlined /> </a>
                <template #overlay>
                  <a-menu>
                    <a-menu-item key="toggle-status" @click="() => handleToggleStatus(record)">
                      {{ record.status === 2 ? '禁用资源' : '启用资源' }}
                    </a-menu-item>
                    <a-menu-item key="delete" @click="() => handleDelete(record)">
                      删除
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 预览资源模态框 -->
    <a-modal
      v-model:open="previewModalVisible"
      :title="previewResource?.name || '资源预览'"
      @cancel="handlePreviewCancel"
      width="80%"
      style="top: 20px"
      :footer="null"
    >
      <div class="file-preview-container" v-if="previewResource">
        <!-- Word文档预览 -->
        <template v-if="previewResource.type === 'docx'">
          <vue-office-docx
            :src="previewResource.fileUrl"
            :config="{ width: '100%', height: '70vh' }"
          />
        </template>
        <!-- PDF预览 -->
        <template v-else-if="previewResource.type === 'pdf'">
          <vue-office-pdf
            :src="previewResource.fileUrl"
            :config="{ width: '100%', height: '70vh' }"
          />
        </template>
        <!-- Excel预览 -->
        <template v-else-if="previewResource.type === 'xlsx'">
          <vue-office-excel
            :src="previewResource.fileUrl"
            :config="{ width: '100%', height: '70vh' }"
          />
        </template>
        <!-- 其他文件类型 -->
        <template v-else>
          <div class="unsupported-file-type">
            <file-unknown-outlined style="font-size: 48px; color: #faad14" />
            <p>暂不支持该类型文件的预览，请下载后查看</p>
            <a-button type="primary" @click="() => handleDownload(previewResource)"
              >下载文件</a-button
            >
          </div>
        </template>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import {
  UploadOutlined,
  DeleteOutlined,
  ReloadOutlined,
  DownOutlined,
  InboxOutlined,
  FilePdfOutlined,
  FileWordOutlined,
  FileExcelOutlined,
  FilePptOutlined,
  FileOutlined,
  PictureOutlined,
  VideoCameraOutlined,
  SoundOutlined,
  FileUnknownOutlined,
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import {
  deleteResource,
  listResourceByPage,
  updateResource,
} from '@/api/resourceController'
import dayjs from 'dayjs'
import { downloadFile } from '@/utils/file/download'
import VueOfficeDocx from '@vue-office/docx'
import VueOfficePdf from '@vue-office/pdf'
import VueOfficeExcel from '@vue-office/excel'

// 表格列定义
const columns = [
  {
    title: '#',
    key: 'id',
    width: 200,
  },
  {
    title: '预览',
    key: 'preview',
    width: 80,
  },
  {
    title: '资源名称',
    dataIndex: 'name',
    key: 'name',
    sorter: true,
    ellipsis: true,
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true,
  },
  {
    title: '类型',
    key: 'type',
    dataIndex: 'type',
    filters: [
      { text: 'PDF文档', value: 'pdf' },
      { text: 'Word文档', value: 'word' },
      { text: 'Excel表格', value: 'excel' },
      { text: 'PPT演示', value: 'ppt' },
      { text: '图片', value: 'image' },
      { text: '视频', value: 'video' },
      { text: '音频', value: 'audio' },
      { text: '其他', value: 'other' },
    ],
    width: 100,
  },
  {
    title: '大小',
    dataIndex: 'fileSize',
    key: 'fileSize',
    sorter: true,
    width: 100,
  },
  {
    title: '上传者',
    dataIndex: 'userName',
    key: 'userName',
    width: 120,
  },
  {
    title: '上传时间',
    dataIndex: 'publishTime',
    key: 'publishTime',
    sorter: true,
    width: 170,
  },
  {
    title: '状态',
    key: 'status',
    dataIndex: 'status',
    // 状态（1草稿/2已发布/3下架/4等待中/5生成中/6失败）
    filters: [
      { text: '可用', value: 2 },
      { text: '已禁用', value: 3 },
    ],
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
  },
]

//搜索条件 复用分页查询的接口
const searchParams = reactive<API.ResourceQueryRequest>({
  current: 1,
  pageSize: 10, //固定只能展示3个数据
})

// 分页配置
const pagination = computed(() => {
  return {
    current: searchParams.current ?? 1, //有则按照传过来的，否则默认为1
    pageSize: searchParams.pageSize ?? 10, //默认为 10
    total: Number(total.value) ?? 0, //默认为 0
    showSizeChanger: true,
    showTotal: (total) => `共${total}条数据`,
  }
})
// 处理表格变更（排序、筛选等）
const handleTableChange = (page: any, filters: any, sorter: any) => {
  // 更新分页
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}
//资源列表
const total = ref(0)
const dataList = ref<API.AdminResourceVO[]>([])
const fetchData = async () => {
  try {
    const res = await listResourceByPage({
      ...searchParams,
    })
    if (res.data.data && res.data.code === 0) {
      dataList.value = res.data.data.records || []
    } else {
      message.error('获取资源列表失败')
    }
  } catch (e) {
    message.error('获取资源列表失败')
  }
}
onMounted(() => {
  fetchData()
})
// 表格加载状态
const loading = ref(false)

// 选中的行
const selectedRowKeys = ref<string[]>([])

// 预览相关
const previewModalVisible = ref(false)
const previewResource = ref<any>(null)

// 表格选择变更
const onSelectChange = (keys: string[]) => {
  selectedRowKeys.value = keys
}

// 搜索
const handleSearch = (value: string) => {
  loading.value = true
  fetchData()
  searchParams.current = 1
  loading.value = false
}

// 获取类型文本
const getTypeText = (type: string) => {
  switch (type) {
    case 'pdf':
      return 'PDF文档'
    case 'doc':
      return 'Word文档'
    case 'docx':
      return 'Word文档'
    case 'xlsx':
      return 'Excel表格'
    case 'pptx':
      return 'PPT演示'
    case 'image':
      return '图片'
    case 'video':
      return '视频'
    case 'audio':
      return '音频'
    default:
      return '其他'
  }
}

// 获取类型颜色
const getTypeColor = (type: string) => {
  switch (type) {
    case 'pdf':
      return 'red'
    case 'doc':
      return 'blue'
    case 'docx':
      return 'blue'
    case 'xlsx':
      return 'green'
    case 'pptx':
      return 'orange'
    case 'image':
      return 'purple'
    case 'video':
      return 'magenta'
    case 'audio':
      return 'cyan'
    default:
      return 'default'
  }
}

// 获取预览文本
const getPreviewText = (type: string) => {
  switch (type) {
    case 'pdf':
      return 'PDF文档预览，实际项目中将集成PDF预览器'
    case 'word':
      return 'Word文档预览，实际项目中将集成Office预览'
    case 'excel':
      return 'Excel表格预览，实际项目中将集成Office预览'
    case 'ppt':
      return 'PPT演示文稿预览，实际项目中将集成Office预览'
    case 'image':
      return '图片预览，实际项目中将显示图片'
    case 'video':
      return '视频预览，实际项目中将集成视频播放器'
    case 'audio':
      return '音频预览，实际项目中将集成音频播放器'
    default:
      return '该类型文件不支持在线预览，请下载后查看'
  }
}

// 处理切换状态
const handleToggleStatus = async (record: any) => {
  const newStatus = record.status === 2 ? 3 : 2
  try {
    const res = await updateResource({
      id: record.id,
      status: newStatus,
    })
    if (res.data.data && res.data.code === 0) {
      await fetchData()
      message.success(`已${newStatus === 2 ? '启用' : '禁用'}资源: ${record.name}`)
    } else {
      message.error(`${newStatus === 2 ? '启用' : '禁用'}用户 ${record.username}失败`)
    }
  } catch (e) {
    message.error(`已${newStatus === 2 ? '启用' : '禁用'}用户 ${record.username}失败`)
  }
}

// 处理预览
const handlePreview = (record: any) => {
  previewResource.value = record
  previewModalVisible.value = true
}

// 处理预览取消
const handlePreviewCancel = () => {
  previewModalVisible.value = false
}

// 处理下载
const handleDownload = (record: any) => {
  downloadFile(record?.fileUrl, record?.name)
  message.success(`开始下载: ${record.name}`)
}

// 处理删除
const handleDelete = async (record: any) => {
  try {
    const res = await deleteResource({
      id: record.id,
    })
    if (res.data.data && res.data.code === 0) {
      await fetchData()
      message.success(`已删除资源 ${record.name}`)
    } else {
      message.error(`删除资源 ${record.name}失败`)
    }
  } catch (e) {
    message.error(`删除资源 ${record.name}失败`)
  }
}
const cancel = (e: MouseEvent) => {}

// 处理批量删除
const handleBatchDelete = () => {
  if (selectedRowKeys.value.length === 0) return

  // 实际项目中这里会调用API批量删除资源
  message.success(`已删除 ${selectedRowKeys.value.length} 个资源`)
  selectedRowKeys.value = []
}
</script>

<style scoped>
.resource-admin-container {
  padding-top: 20px;
  padding-bottom: 40px;
}

.page-title {
  font-size: 24px;
  margin-bottom: 24px;
  color: var(--primary-color);
}

.section-card {
  margin-bottom: 24px;
  border-radius: 8px;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.left,
.right {
  display: flex;
  align-items: center;
}

.resource-preview {
  font-size: 24px;
  color: var(--primary-color);
}

.preview-container {
  padding: 16px;
}

.preview-info {
  margin-bottom: 24px;
}

.preview-header {
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--border-color);
}

.preview-header h3 {
  margin-bottom: 8px;
  color: var(--text-color);
}

.preview-header p {
  color: var(--text-color-light);
}

.preview-meta {
  display: flex;
  flex-wrap: wrap;
}

.meta-item {
  width: 33.33%;
  margin-bottom: 16px;
}

.meta-label {
  font-size: 12px;
  color: var(--text-color-light);
  margin-bottom: 4px;
}

.meta-value {
  font-size: 14px;
  color: var(--text-color);
}

.preview-content {
  height: 300px;
  border: 1px solid var(--border-color);
  border-radius: 8px;
  overflow: hidden;
}

.preview-placeholder {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 16px;
  background-color: var(--background-color);
}

.preview-placeholder > span {
  font-size: 48px;
  margin-bottom: 16px;
  color: var(--primary-color);
}

.preview-placeholder p {
  text-align: center;
  color: var(--text-color-light);
}
.file-preview-container {
  min-height: 400px;
  background: #f6faff;
  border-radius: 8px;
  padding: 24px 12px;
}
.unsupported-file-type {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 60vh;
  color: #faad14;
}
.unsupported-file-type p {
  margin: 16px 0 12px;
  color: #888;
}
</style>
